package com.travel.bhelp.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.travel.bhelp.common.model.Result;
import com.travel.bhelp.user.model.User;
import com.travel.bhelp.user.repository.UserMapper;
import com.travel.bhelp.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result register(User user) {
        // 检查用户名是否已存在
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        if (userMapper.selectCount(wrapper) > 0) {
            return Result.error(400, "用户名已存在");
        }

        // 密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        user.setStatus(1); // 默认激活状态
        userMapper.insert(user);
        return Result.success("注册成功");
    }

    @Override
    public Result login(String username, String password) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userMapper.selectOne(wrapper);
        
        if (user == null) {
            return Result.error(400, "用户不存在");
        }
        
        String encryptedPwd = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!encryptedPwd.equals(user.getPassword())) {
            return Result.error(400, "密码错误");
        }
        
        // TODO: 生成token并返回
        return Result.success("登录成功");
    }

    @Override
    public Result logout(String token) {
        // TODO: 实现token失效逻辑
        return Result.success("注销成功");
    }

    @Override
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }
}
